package com.cungmua.app.base;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import com.cungmua.app.R;
import com.cungmua.app.activity.BuyActivity;
import com.cungmua.app.activity.CategoryActivity;
import com.cungmua.app.activity.ChooseCityActivity;
import com.cungmua.app.activity.CreateAddressShipingActivity;
import com.cungmua.app.activity.DealDetailsActivity;
import com.cungmua.app.activity.EditProfileActivity;
import com.cungmua.app.activity.FeatueredActivity;
import com.cungmua.app.activity.FinishedActivity;
import com.cungmua.app.activity.ListDealActivity;
import com.cungmua.app.activity.LoginActivity;
import com.cungmua.app.activity.MakeOrderActivity;
import com.cungmua.app.activity.MapAddressActivity;
import com.cungmua.app.activity.OrderHistoryActivity;
import com.cungmua.app.activity.YourCartActivity;
import com.cungmua.app.model.Cart;
import com.cungmua.app.model.Category;
import com.cungmua.app.model.City;
import com.cungmua.app.model.DealDetails;
import com.cungmua.app.model.ShippingAddress;
import com.cungmua.app.model.User;
import com.cungmua.app.model.request.LoginRequest;
import com.cungmua.app.utils.JsonUtils;
import com.cungmua.app.utils.PrefUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by kelvin.nguyen on 6/16/14.
 */
public abstract class BaseActivity extends SlidingFragmentActivity{
    public static final String USER_KEY = "user";
    public static final String LIST_CITY_KEY = "city_list";
    public static final String KEY_SEARCH = "keyword";
    public static final String CITY_KEY = "city";
    public static final String LIST_CATEGORY_KEY = "category_list";
    public static final String LOGIN_REQUEST_KEY = "login_request";
    public static final String CART_KEY = "cart";
    public static final int REQUEST_LOGIN = 1;
    public static final int REQUEST_CREATE_ADDRESS = 2;
    public static final int REQUEST_EDIT_ADDRESS = 3;
    public static final int REQUEST_PAYMENT = 4;
    public static final int REQUEST_REGISTER = 5;
    public static final int REQUEST_EDIT_PROFILE = 6;
    public static final int REQUEST_CHANGE_PASS = 7;
    public static final int REQUEST_YAHOO_LOGIN = 8;
    public static final int REQUEST_GOOGLE_LOGIN = 9;
    public static final String IK_CATEGORY_ID = "IK_CATEGORY_ID";
    public static final String IK_DEAL_ID = "IK_DEAL_ID";
    public static final String IK_TYPE_CONTENT = "IK_TYPE_CONTENT";
    public static final String IK_DEAL_DETAILS = "IK_DEAL_DETAILS";
    public static final String IK_PAYMENT_URL = "IK_PAYMENT_URL";
    public static final String IK_RESULT_URL = "IK_RESULT_URL";
    public static final String IK_ORDER_ID = "orderId";
    public static final String IK_USER = "IK_USER";
    public static final String IK_METHOD = "IK_METHOD";
    public static final String IK_UID = "IK_UID";
    public static final String IK_EMAIL = "IK_EMAIL";
    public static final String IK_AUTH_TOKEN = "IK_AUTH_TOKEN";
    public static final String IK_METHOD_YAHOO = "IK_METHOD_YAHOO";
    public static final String IK_METHOD_GOOGLE = "IK_METHOD_GOOGLE";

    public static final String SHIPPING_ADDRESS_KEY = "shipping_address";
    public static final String IK_BANK = "IK_BANK";
    public static final String KEY_TITLE = "title";
    public static final String KEY_FEATURED = "Điểm nổi bật";
    public static final String KEY_NOTE = "Lưu ý khi mua";
    public static final String KEY_ADDRESS = "Địa chỉ sử dụng";
    public static final String KEY_PROMOTION = "Chi tiết khuyến mãi";
    public static final int KEY_DEFAULT_FEE = 25000;


    public static final int THONGTIN= 11111;
    public static final int THONGTIN_TAIKHOAN= 1212121212;
    public static final int THONGTIN_TAIKHOAN_DANGNHAP= 999999;
    public static final int THONGTIN_TAIKHOAN_DANGKY= 888888;

//    =============Login success =========
        public static final int LOGINED_THONGTIN_TAIKHOAN= 777777;
        public static final int LOGINED_THONGTIN_DONHANG= 666666;
        public static final int LOGINED_THONGTIN_TIENTHUONG= 555555;
        public static final int LOGINED_THONGTIN_TAIKHOAN_PREMIUM= 444444;
        public static final int LOGINED_THONGTIN_DOIMATKHAU= 333333;
        public static final int LOGINED_THONGTIN_DANGXUAT= 222222;


//    ================Thong Tin Huu Ich ======
        public static final int THONGTIN_HUUICH_ABOUT= 159;
        public static final int THONGTIN_HUUICH_QUYCHE= 951;
        public static final int THONGTIN_HUUICH_TRAHANG= 753;
        public static final int THONGTIN_HUUICH_HUONGDAN= 357;
        public static final int THONGTIN_HUUICH_HINHTHUC= 852;
        public static final int THONGTIN_HUUICH_HINHTHUC_GIAO= 258;


    public static final int THONGTIN_HUUICH= 1313131313;
    public static final int SELECT_CITY= 1515151515;
    public static final int DEFAULT_CITY= 1616161616;
    public static final int LOGIN= 1717171717;
    public static final int DANHMUC=33333 ;
    public static final int HOME= 1;
    public static final int PROMOTION=2 ;
//    public static final int thongtin= ;

//    ================Drawer menu =======

    public static final int ICON_DRAW_FASHION=R.drawable.icon_draw_fashion;
    public static final int ICON_DRAW_FASHION_ACCESSORIES=R.drawable.icon_draw_fashion_accessories;
    public static final int ICON_DRAW_FOOD_RESTAURANT=R.drawable.icon_draw_food_restaurant;
    public static final int ICON_DRAW_HEALTH_BEAUTY=R.drawable.icon_draw_health_beauty;
    public static final int ICON_DRAW_TRAVEL_RESORT=R.drawable.icon_draw_travel_resort;
    public static final int ICON_DRAW_ENTERTAIMENT_EDUCATION=R.drawable.icon_draw_entertaiment_education;
    public static final int ICON_DRAW_HOUSEHOLD_FURNITURE=R.drawable.icon_draw_household_furniture;
    public static final int ICON_DRAW_ELECTRONIC_TECHNOLOGY=R.drawable.icon_draw_electronic_technology;
    public static final int ICON_DRAW_MOTHER_BABY=R.drawable.icon_draw_mother_baby;

    public static final int ICON_DRAW_HOME=R.drawable.icon_draw_home;
    public static final int ICON_DRAW_HOME_PROMOTIONS=R.drawable.icon_draw_home_promotions;
    public static final int ICON_DRAW_LOGOUT=R.drawable.icon_draw_logout;
    public static final int ICON__DRAW_LOGIN=R.drawable.icon__draw_login;
    public static final int ICON__DRAW_REGISTER=R.drawable.icon__draw_register;

    public static final int ICON_DRAW_LOVE=R.drawable.icon_draw_love;
    public static final int ICON_DRAW_FORGOTPASS=R.drawable.icon_draw_forgotpass;
    public static final int ICON_DRAW_MONEY=R.drawable.icon_draw_money;
    public static final int ICON_DRAW_HISTORY=R.drawable.icon_draw_history;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        //Remove title bar
        this.requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

       initActivity(savedInstanceState);

        //	getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    protected void initActivity(Bundle savedInstanceState) {
       setContentView(getLayoutResource());

        setBehindContentView(getLayoutResource());

        loadControls(savedInstanceState);

        updateView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_LOGIN) {
            if (resultCode == RESULT_OK) {
                refreshActivity();
                return;
            }
        } else if (requestCode == REQUEST_REGISTER) {
            if (resultCode == RESULT_OK) {
                refreshActivity();
                return;
            }
        } else if (requestCode == REQUEST_EDIT_PROFILE) {
            if (resultCode == RESULT_OK) {
                refreshActivity();
                return;
            }
        } else if (requestCode == REQUEST_CHANGE_PASS) {
            if (resultCode == RESULT_OK) {
                return;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }



    public String getDeviceId() {
        return Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
    }
    public String getToken() {
        if (getCurrentUser() != null)
            return getCurrentUser().getToken();
        return "";
    }


    public abstract void updateView();

    public abstract void loadControls(Bundle savedInstanceState);

    public int getLayoutResource() {
        return R.layout.activity_deal_list;
    }



    public void refreshActivity() {
        finish();
        startActivity(getIntent());
    }

    public User getCurrentUser() {
        User currentUser;
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            String json = PrefUtils.readPreferences(this, USER_KEY, "");
            currentUser = mapper.readValue(json, User.class);
        } catch (IOException e) {
            e.printStackTrace();
            return User.defaultUser();
        }
        if (currentUser.getToken() == null)
            return User.defaultUser();

        return currentUser;
    }

    public void setCurrentCity(City city) {
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            PrefUtils.savePreferences(this, CITY_KEY, mapper.writeValueAsString(city));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public void editProfile(User user) {
        Intent intent = new Intent(this, EditProfileActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        intent.putExtra(IK_USER, user);
        startActivityForResult(intent, REQUEST_EDIT_PROFILE);
    }

    public void gotoCreateAddress(ShippingAddress address) {
        Intent intent = new Intent(this, CreateAddressShipingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
//        intent.putExtra(IK_USER, user);
        intent.putExtra(SHIPPING_ADDRESS_KEY,address);
        startActivityForResult(intent, REQUEST_CREATE_ADDRESS);
    }

    public void gotoEditAddress(ShippingAddress address) {
        Intent intent = new Intent(this, CreateAddressShipingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EDIT", true);
//        intent.putExtra(IK_USER, user);
        intent.putExtra(SHIPPING_ADDRESS_KEY,address);
        startActivityForResult(intent, REQUEST_CREATE_ADDRESS);
    }




    public City getCurrentCity() {
        City currentCity;
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            String json = PrefUtils.readPreferences(this, CITY_KEY, "");
            currentCity = mapper.readValue(json, City.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return currentCity;
    }

    public void setCurrentUser(User user) {

        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            PrefUtils.savePreferences(this, USER_KEY, mapper.writeValueAsString(user));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public void setLastLoginRequest(LoginRequest request) {
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            PrefUtils.savePreferences(this, LOGIN_REQUEST_KEY, mapper.writeValueAsString(request));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public Cart getCurrentCart() {
        Cart currentCart;
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            String json = PrefUtils.readPreferences(this, CART_KEY, "");
            currentCart = mapper.readValue(json, Cart.class);
        } catch (IOException e) {
            e.printStackTrace();
            return new Cart();
        }

        return currentCart;
    }

    public void setCurrentCart(Cart cart) {
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            PrefUtils.savePreferences(this, CART_KEY, mapper.writeValueAsString(cart));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public List<Category> getCategoryList() {
        List<Category> categoryList;
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            String json = PrefUtils.readPreferences(this, LIST_CATEGORY_KEY, "");
            categoryList = mapper.readValue(json, new TypeReference<List<Category>>(){});
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<Category>();
        }

        return categoryList;
    }


    public void setCityList(List<City> data) {
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            PrefUtils.savePreferences(this, LIST_CITY_KEY, mapper.writeValueAsString(data));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public void setCategoryList(List<Category> categories) {
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            PrefUtils.savePreferences(this, LIST_CATEGORY_KEY, mapper.writeValueAsString(categories));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public void login() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, REQUEST_LOGIN);
    }


    public void goToDealDetail(int dealId) {
        Intent intent = new Intent(this, DealDetailsActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        intent.putExtra(IK_DEAL_ID, dealId);
        startActivity(intent);
    }

    public void goToHotDeal() {
        Intent intent = new Intent(this, ListDealActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }
    public void goToHotDeal(boolean clear) {
        Intent intent = new Intent(this, ListDealActivity.class);
        if (clear)
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    protected void goToChooseCity() {
        Intent intent = new Intent(this, ChooseCityActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }


    public void goToCategory(int categoryId, String name) {
        Intent intent = new Intent(this, CategoryActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        intent.putExtra(IK_CATEGORY_ID, categoryId);
        intent.putExtra("TITLE",name);
        startActivity(intent);
    }

    public void goToBuy(DealDetails details) {
        Intent intent = new Intent(this, BuyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        intent.putExtra(IK_DEAL_DETAILS, details);
        startActivity(intent);
    }
    public void goToYourCart() {
        Intent intent = new Intent(this, YourCartActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }

    public void goToDealFeatured(int dealId,String title) {
        Intent intent = new Intent(this, FeatueredActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        intent.putExtra(KEY_TITLE, title);
        intent.putExtra(IK_DEAL_ID, dealId);
        startActivity(intent);
    }

    public void goToCall(String phone){
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:"+phone));
        startActivity(callIntent);
    }
    public void goToDealMapAddress(int dealId,String title) {
        Intent intent = new Intent(this, MapAddressActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        intent.putExtra(KEY_TITLE, title);
        intent.putExtra(IK_DEAL_ID, dealId);
        startActivity(intent);
    }



    public void goToMakeOrder(String totalPrice) {
        Intent intent = new Intent(this, MakeOrderActivity.class);
        intent.putExtra("TOTAL_PRICE", totalPrice);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }

    public void goToFinished(long orderId,ArrayList<String> result) {
        Intent intent = new Intent(this, FinishedActivity.class);
        intent.putExtra(IK_ORDER_ID, orderId);
        intent.putStringArrayListExtra(IK_BANK,result);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }

    public void goToPastDeals() {
        Intent intent = new Intent(this, OrderHistoryActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("EXIT", true);
        startActivity(intent);
    }


    public Category getCategoryById(int categoryId) {
        List<Category> categoryList = getCategoryList();
        for (Category cate: categoryList) {
            if (cate.getId() == categoryId)
                return cate;
            if (cate.getChildren() != null)
                for (Category sub: cate.getChildren())
                    if (sub.getId() == categoryId)
                        return sub;
        }
        return null;
    }

    /**
     *
     * @return
     */
    public List<City> getCityList() {
        List<City> cityList;
        ObjectMapper mapper = JsonUtils.defaultMapper();
        try {
            String json = PrefUtils.readPreferences(this, LIST_CITY_KEY, "");
            cityList = mapper.readValue(json, new TypeReference<List<City>>(){});
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<City>();
        }

        return cityList;
    }


    public void alert(String message) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(message)
                .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
    }
}
